package com.insight.modules.quartz.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import com.insight.common.api.vo.Result;
import com.insight.common.constant.CommonConstant;
import com.insight.common.system.base.controller.JeecgController;
import com.insight.common.system.query.QueryGenerator;
import com.insight.common.system.vo.LoginUser;
import com.insight.common.util.ImportExcelUtil;
import com.insight.modules.quartz.entity.QuartzJob;
import com.insight.modules.quartz.service.IQuartzJobService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: Quartz 定时任务在线管理
 * @Author: jeecg-boot
 * @Date: 2019-01-02
 * @Version:V1.0
 */
@RestController
@RequestMapping("/sys/quartzJob")
@Slf4j
@Api(tags = "定时任务接口")
public class QuartzJobController extends JeecgController<QuartzJob, IQuartzJobService> {
	@Autowired
	private IQuartzJobService quartzJobService;

    private static final String orderClassName = "com.yuanqiao.insight.accountbook.modules.orderFrom.service.impl.DevopsOrderFromServiceImpl";

	/**
	 * 分页列表查询
	 *
	 * @param quartzJob
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public Result<?> queryPageList(QuartzJob quartzJob, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		String jobClassName = quartzJob.getJobClassName();
		if(StringUtils.isNotBlank(jobClassName)){
			quartzJob.setJobClassName(null);
		}
		QueryWrapper<QuartzJob> queryWrapper = QueryGenerator.initQueryWrapper(quartzJob, req.getParameterMap());
		queryWrapper.notLike("job_class_name","DevopsOrderFromServiceImpl")
				.eq("del_flag", "0");//排除人工巡检-巡检配置里的定时任务
		if(StringUtils.isNotBlank(jobClassName)){
			queryWrapper.like("job_class_name",jobClassName);
		}
		Page<QuartzJob> page = new Page<QuartzJob>(pageNo, pageSize);
		IPage<QuartzJob> pageList = quartzJobService.page(page, queryWrapper);
		/*for (QuartzJob record : pageList.getRecords()) {
			record.setNumber(Integer.parseInt(String.format("%.0f", Math.random() * ((10 + 1) - 1) + 1)));
			record.setLastTime(DateUtil.getNow());
			record.setLastStatus(0);
		}*/
        return Result.ok(pageList);

    }

    @RequestMapping(value = "/orderlist", method = RequestMethod.GET)
    public Result<?> queryPageOrderList(QuartzJob quartzJob, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {

        String jobClassName = quartzJob.getOrderName();
        Integer status = quartzJob.getStatus();
        QueryWrapper<QuartzJob> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("job_class_name", orderClassName);
//		QueryWrapper<QuartzJob> queryWrapper = QueryGenerator.initQueryWrapper(quartzJob, req.getParameterMap());
        if (StringUtils.isNotBlank(jobClassName)) {
            queryWrapper.like("order_name", jobClassName);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        queryWrapper.orderByDesc("create_time");
        Page<QuartzJob> page = new Page<QuartzJob>(pageNo, pageSize);
        IPage<QuartzJob> pageList = quartzJobService.page(page, queryWrapper);
        return Result.OK(pageList);

    }

    /**
     * 添加定时任务
     *
     * @param quartzJob
     * @return
     */
    //@RequiresRoles("admin")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<?> add(@RequestBody QuartzJob quartzJob) {
        if (null == quartzJob.getJobClassName()) {
            quartzJob.setJobClassName(orderClassName + "#" + System.currentTimeMillis());
        }
        List<QuartzJob> list = quartzJobService.findByJobClassName(quartzJob.getJobClassName());
        if (CollUtil.isNotEmpty(list)) {
            return Result.OK().error500("该定时任务类名已存在");
        }
        boolean b = quartzJobService.saveAndScheduleJob(quartzJob);
        if (!b) {
            return Result.error("创建定时任务失败");
        }
        return Result.OK().success("创建定时任务成功");
    }

    /**
     * 更新定时任务
     *
     * @param quartzJob
     * @return
     */
    //@RequiresRoles("admin")
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public Result<?> eidt(@RequestBody QuartzJob quartzJob) {
        List<QuartzJob> list = quartzJobService.list(new LambdaQueryWrapper<QuartzJob>()
                .eq(QuartzJob::getJobClassName, quartzJob.getJobClassName())
                .ne(QuartzJob::getId, quartzJob.getId()));
        if (CollUtil.isNotEmpty(list)) {
            return Result.OK().error500("该定时任务类名已存在");
        }
        boolean b = quartzJobService.editAndScheduleJob(quartzJob);
        if (!b) {
            return Result.error("更新定时任务失败");
        }
        return Result.OK().success("更新定时任务成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    //@RequiresRoles("admin")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        QuartzJob quartzJob = quartzJobService.getById(id);
        if (quartzJob == null) {
            return Result.OK().error500("未找到对应实体");
        }
        boolean b = quartzJobService.deleteAndStopJob(quartzJob);
        if (!b) {
            return Result.error("删除定时任务失败");
        }
        return Result.OK().success("删除成功!");

    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    //@RequiresRoles("admin")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.OK().error500("参数不识别！");
        }
        for (String id : Arrays.asList(ids.split(","))) {
            QuartzJob job = quartzJobService.getById(id);
            boolean b = quartzJobService.deleteAndStopJob(job);
            if (!b) {
                return Result.error("删除定时任务失败");
            }
        }
        return Result.OK().success("删除定时任务成功!");
    }

    /**
     * 暂停定时任务
     *
     * @param id
     * @return
     */
    //@RequiresRoles("admin")
    @GetMapping(value = "/pause")
    @ApiOperation(value = "暂停定时任务")
    public Result<Object> pauseJob(@RequestParam(name = "id") String id) {
        QuartzJob job = quartzJobService.getById(id);
        quartzJobService.pause(job);
        return Result.OK().success("暂停定时任务成功");
    }

    /**
     * 启动定时任务
     *
     * @param id
     * @return
     */
    //@RequiresRoles("admin")
    @GetMapping(value = "/resume")
    @ApiOperation(value = "恢复定时任务")
    public Result<Object> resumeJob(@RequestParam(name = "id") String id) {
        QuartzJob job = quartzJobService.getById(id);
        boolean b = quartzJobService.resumeJob(job);
        if (!b) {
            return Result.error("恢复定时任务失败");
        }
        //scheduler.resumeJob(JobKey.jobKey(job.getJobClassName().trim()));
        return Result.OK().success("恢复定时任务成功");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        QuartzJob quartzJob = quartzJobService.getById(id);
        return Result.OK(quartzJob);
    }

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param quartzJob
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, QuartzJob quartzJob) {
		// Step.1 组装查询条件
		QueryWrapper<QuartzJob> queryWrapper = QueryGenerator.initQueryWrapper(quartzJob, request.getParameterMap());
		// Step.2 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		List<QuartzJob> pageList = quartzJobService.list(queryWrapper);
		//过滤选中的数据
		List<QuartzJob> exportList = super.selectionsFilter(request, pageList);
		// 导出文件名称
		mv.addObject(NormalExcelConstants.FILE_NAME, "定时任务列表");
		mv.addObject(NormalExcelConstants.CLASS, QuartzJob.class);
		LoginUser principal = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("定时任务列表数据", "导出人:" + principal.getRealname(),"导出信息"));
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (request == null) {
            return Result.OK().error500("请求对象为空");
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (fileMap == null || fileMap.isEmpty()) {
            return Result.OK().error500("未包含上传文件");
        }
        List<String> errorMessage = new ArrayList<>();
        int successLines = 0, errorLines = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            if (entity == null || entity.getValue() == null) {
                continue;
            }
            MultipartFile file = entity.getValue();
            try (InputStream inputStream = file.getInputStream()) {
                ImportParams params = new ImportParams();
                params.setTitleRows(2);
                params.setHeadRows(1);
                params.setNeedSave(true);
                List<Object> listQuartzJobs = ExcelImportUtil.importExcel(inputStream, QuartzJob.class, params);
                if (listQuartzJobs != null) {
                    List<String> list = ImportExcelUtil.importDateSave(listQuartzJobs, IQuartzJobService.class, errorMessage, CommonConstant.SQL_INDEX_UNIQ_JOB_CLASS_NAME);
                    errorLines += list.size();
                    successLines += (listQuartzJobs.size() - list.size());
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.OK().error500("文件导入失败！");
            }
        }
        return ImportExcelUtil.imporReturnRes(errorLines, successLines, errorMessage);
    }

    /**
     * 立即执行
     *
     * @param id
     * @return
     */
    //@RequiresRoles("admin")
    @GetMapping("/execute")
    public Result<?> execute(@RequestParam(name = "id", required = true) String id) {
        if (StringUtils.isEmpty( id)){
            return Result.OK().error500("参数不识别！");
        }
        QuartzJob quartzJob = quartzJobService.getById(id);
        if (quartzJob == null) {
            return Result.OK().error500("未找到对应实体");
        }
        try {
            quartzJobService.execute(quartzJob);
        } catch (Exception e) {
            //e.printStackTrace();
            log.info("定时任务 立即执行失败>>" + e.getMessage());
            return Result.OK().error500("执行失败!");
        }
        return Result.OK().success("执行成功!");
    }
}
